#include "stdafx.h"
#include "TextureDrawObject.h"


TextureDrawObject::TextureDrawObject()
{
	m_renders = new Render;
	m_numRender = 1;
	m_vertexDatas[topLeft].uv = glm::vec2(0.f, 0.f);
	m_vertexDatas[topRight].uv = glm::vec2(1.f, 0.f);
	m_vertexDatas[bottomLeft].uv = glm::vec2(0.f, 1.f);
	m_vertexDatas[bottomRight].uv = glm::vec2(1.f, 1.f);
}

TextureDrawObject::TextureDrawObject(Camera *camera, Texture *tex, Shader *shader) : TextureDrawObject()
{
	Init(camera, tex, shader);
}

TextureDrawObject::~TextureDrawObject()
{
}

VaoMesh *TextureDrawObject::GetTextureMesh()
{
	static VaoMesh *mesh;
	if (!mesh)
	{
		mesh = new VaoMesh(GL_STREAM_DRAW);
		//mesh->SetVboDrawInstanceData(&Shaders::GetInstance()->m_vboDrawInstanceData);
		int stride = sizeof(VertexData);
		VertexAttribPointerParam params[3];
		params[0].Set(0, 2, GL_FLOAT, false, stride);
		params[1].Set(1, 2, GL_FLOAT, false, stride, (const void*)offsetof(VertexData, uv));
		params[2].Set(2, 4, GL_FLOAT, false, stride, (const void*)offsetof(VertexData, color));
		mesh->GenVaoVbo(nullptr, 4, sizeof(VertexData), params, 3, nullptr, 0, 0);
		VaoMesh::SubMesh submesh;
		submesh.mode = GL_TRIANGLE_FAN;
		submesh.vertElementLocation = 0;
		submesh.vertElementCount = 4;
		mesh->m_subMeshs.push_back(submesh);
	}
	return mesh;
}

void TextureDrawObject::Init(Camera *camera, Texture *tex, Shader *shader)
{
	m_width = tex->sz.cx;
	m_height = tex->sz.cy;
	RenderObject::Init(camera, 1);
	Material *mate = new Material;
	mate->m_textures.push_back(tex);
	mate->m_shader = shader;
	m_renders[0].SetMesh(GetTextureMesh());
	m_renders[0].SetMaterial(0, mate);
	MakeVertexs();
}

void TextureDrawObject::SetTexcoord(glm::vec2 uvs[4])
{
	auto puv = uvs;
	for (auto &vert : m_vertexDatas)
	{
		vert.uv = *puv;
		puv++;
	}
}

void TextureDrawObject::SetSize(float w, float h)
{
	m_width = w;
	m_height = h;
	MakeVertexs();
}

void TextureDrawObject::SetAnchorPoint(glm::vec2 &pt)
{
	m_anchorPoint = pt;
	MakeVertexs();
}

void TextureDrawObject::SetVertexColor(VertexPosition pos, glm::vec4 &color)
{
	m_vertexDatas[pos].color = color;
}

void TextureDrawObject::MakeVertexs()
{
	float x, y;
	x = -m_width * m_anchorPoint.x;
	y = -m_height * m_anchorPoint.y;

	m_vertexDatas[topLeft].pos.x = x;
	m_vertexDatas[topLeft].pos.y = y + m_height;

	m_vertexDatas[topRight].pos.x = x + m_width;
	m_vertexDatas[topRight].pos.y = y + m_height;

	m_vertexDatas[bottomLeft].pos.x = x;
	m_vertexDatas[bottomLeft].pos.y = y;

	m_vertexDatas[bottomRight].pos.x = x + m_width;
	m_vertexDatas[bottomRight].pos.y = y;
}

void TextureDrawObject::Draw()
{
	m_renders[0].m_vaoMesh->UpdateVbo(0, sizeof(VertexData) * 4, m_vertexDatas);
	RenderObject::Draw();
}